import { ref, inject, getCurrentInstance, computed } from 'vue';
// import { request } from '@common/core';
import core from '@common/core'
const request = core.getExportResource('src/core/utils/http-tools.js').default;
export default function useCommon(formData, isEdit = false) {
  const { commandFunc } = inject('apiFunTools');
  const { proxy } = getCurrentInstance();
  const formRef = ref(null);
  const ibaForm = ref(null);
  const tyProjectForm = ref({
    formData: []
  });
  const notSpecialChar = ref('');
  const phaseOptions = ref({
    list: [],
    placeholder: proxy.$t('plsSelect'),
    props: { label: 'displayName', value: 'name' }
  });
  const isAddparameter = computed(() => {
    return {
      type: 'ty.inteplm.project.CTyProject',
      containerOid: '0',
      containerOtype: 'ty.inteplm.project.CTyProject',
      typeOid: formData.value.typeOid
    };
  });
  const getAttrValueTableByEntitys = (name) => {
    let param = {
      otype: formData.value.otype,
      oidAndLogicalList: [
        {
          oid: formData.value.oid,
          logicalIdentifier: name
        }
      ],
      isAdapter: true
    };
    commandFunc('$rpmapis', 'project', 'getAttrValueTableByEntitys', param, {
      callback: (res) => {
        if (res) {
          let ibaAttributeMap = res[formData.value.oid];
          tyProjectForm.value.formData.forEach((item) => {
            const attrVals = ibaAttributeMap[item.name];
            item.value = attrVals ? (attrVals.length > 1 ? attrVals : attrVals[0]) : '';
          });
        }
      }
    });
  };
  const getIbaForm = (name) => {
    commandFunc('$rpmapis', 'project', 'getIbaByLogicalIdentifier', name, {
      callback: (res) => {
        tyProjectForm.value = res || {};
        formData.value.tyProjectForm = res || {};
        if (isEdit && res?.formData?.length) {
          getAttrValueTableByEntitys(name);
        }
      }
    });
  };
  const getPhaseList = () => {
    const callback = (res) => {
      phaseOptions.value.list = res;
      if (!isEdit && res.length) {
        formData.value.phase = res[0].name;
      }
    };
    commandFunc('$rpmapis', 'project', 'queryAllEnumerationItemByDefName', 'phase', {
      callback
    });
  };
  const getNotSpecialChar = () => {
    const callback = (res) => {
      notSpecialChar.value = res;
    };
    commandFunc('$rpmapis', 'project', 'getNotSpecialChar', null, {
      callback
    });
  };
  const getibaMap = () => {
    let ibaAttributeMap = {};
    if (tyProjectForm?.value?.formData) {
      tyProjectForm.value.formData.forEach((el) => {
        if (el.isIbaProperty && el.isShow) {
          let val = [el.value];
          if (Array.isArray(el.value)) {
            val = el.value;
          }
          ibaAttributeMap[el.prop] = val;
        }
      });
    }
    return ibaAttributeMap;
  };
  const validatorName = async (rule, value, callback) => {
    if (!value) {
      callback(new Error(`${proxy.$t('projectName')}${proxy.$t('required')}`));
      return;
    }
    let nameReg = new RegExp('[' + notSpecialChar.value + ']', 'g');
    const trimReg = /^\s+|\s+$/;
    if (nameReg.test(value) || trimReg.test(value)) {
      callback(new Error(`${proxy.$t('notSpecialChar')}${notSpecialChar.value}`));
      return;
    }
    if (value.length > 200) {
      callback(new Error(`${proxy.$t('projectName')}${proxy.$t('maxLength')}200`));
      return;
    }
    if (!isEdit) {
      const res = await commandFunc('$rpmapis', 'project', 'checkProjectName', {
        number: 1,
        projectName: value
      });
      if (!res) {
        callback(new Error(`${proxy.$t('projectName')}${proxy.$t('existing')}`));
      }
    }
  };

  const validatorNumber = async (rule, value, callback) => {
    if (!value) {
      callback(new Error(`${proxy.$t('projectNumber')}${proxy.$t('required')}`));
      return;
    }
    if (value?.length > 100) {
      callback(new Error(`${proxy.$t('projectNumber')}${proxy.$t('rpm.message.maxLength', { number: 100 })}`));
      return;
    }
    const res = await commandFunc('$rpmapis', 'project', 'checkProjectNumber', {
      number: 1,
      projectNumber: value
    });
    if (!res) {
      callback(new Error(`${proxy.$t('projectNumber')}${proxy.$t('existing')}`));
    }
  };
  const valideIbaForm = () => {
    return new Promise((resolve, reject) => {
      formRef.value.getFormRef().validate((valide) => {
        if (valide) {
          if (ibaForm.value?.handleSubmitForm) {
            ibaForm.value
              .handleSubmitForm()
              .then(() => {
                const ibaAttribute = getibaMap();
                formData.value.ibaAttribute = ibaAttribute;
                resolve(valide);
              })
              .catch(() => {
                proxy.$message.warning(proxy.$t('请完善扩展属性信息！'));
                reject(false);
              });
          } else {
            resolve(valide);
          }
        } else {
          proxy.$message.warning(proxy.$t('请完善基本属性信息！'));
          reject(false);
        }
      });
    });
  };
  const queryDevOrderByNumber = (projectCode = "",pageNum = 1,pageSize = 5) => {
    return new Promise((resolve) => {
      // if (!number) {
      //   proxy.$message.warning('请输入开发令编号');
      //   resolve({ data: [], total: 0 });
      //   return;
      // }
      request({
        method: 'get',
        url: '/rest/v1/devorder/queryAll',
        params: { 
          projectCode,
          pageNum,
          pageSize
        },
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then((res) => {
          console.log("开发令返回值：",res)
          // 检查API响应是否成功
          // if (!res?.data?.success) {
          //   proxy.$message.error(res?.data?.message || '查询失败');
          //   resolve({ data: [], total: 0 });
          //   return;
          // }
          // 根据返回的数据结构，res.data.data 是数组
          const responseData = res?.data?.data.list || [];
          const data = responseData.map((item) => ({
            id: item.oid,
            dev: item.devOrderNumber,
            model: item.aircraftModel,
            number: item.projectCode,
            name: item.projectName,
            level: item.devCategory,
            subLevel: item.devLevel,
            system: item.coefficient,
            owner: item.responsiblePerson,
            remarks: item.remarks,
            createdBy: item.createdBy,
            createdTime: item.createdTime,
            disabledBy: item.disabledBy,
            disabledTime: item.disabledTime,
            isDisabled: item.isDisabled,
            isDelete: item.isDelete,
            boost: item.boost,
            developmentType: item.developmentType,
            productSeries:item.productSeries,
            productCategory: item.productCategory,
            sector:item.sector,
          }));
          resolve({
            data,
            total: res?.data?.data?.total || responseData.length
          });
        })
        .catch(() => {
          proxy.$message.error('查询失败');
          resolve({ data: [], total: 0 });
        });
    });
  };

  const queryDevOrderDetailByProjectCode = (projectCode) => {
    return new Promise((resolve) => {
      if (!projectCode) {
        proxy.$message.warning('请输入项目编号');
        resolve(null);
        return;
      }
      request({
        method: 'get',
        url: '/rest/v1/devorder/queryByprojectCode',
        params: { projectCode },
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then((res) => {
          // 检查API响应是否成功
          if (!res?.data?.success) {
            proxy.$message.error(res?.data?.message || '查询失败');
            resolve(null);
            return;
          }
          // 返回详细信息数据
          resolve(res?.data?.data || null);
        })
        .catch(() => {
          proxy.$message.error('查询失败');
          resolve(null);
        });
    });
  };

  //获取项目模板下拉数据
  const getProjectTemplateList = (params) => {
    return request({
      method: 'post',
      url: '/typrjmng/api/v1/ppm/getAllChildrenByParentPlus',
      data: params,
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then((res) => {
        console.log(res.data);
        return res.data;
      })
      .catch((e) => {
        proxy.$message.error(e?.message || '查询失败');
      });
  };
  //获取选择项目的校验
  const getIbaFormpro = () => {
    return request({
      method: 'get',
      url: '/rest/v1/devorder/getEnum',
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
      .then((res) => {
        return res.data;
      })
      .catch((e) => {
        proxy.$message.error(e?.message || '查询失败');
      });
  };

  //转换字段内容回写模板
  const getEnum = (data) => {
    return request({
      method: 'get',
      url: '/rest/v1/devorder/getEnum',
      data: data,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
      .then((res) => {
        return res.data;
      })
      .catch((e) => {
        proxy.$message.error(e?.message || '查询失败');
      });
  };
  return {
    getEnum,
    formRef,
    ibaForm,
    formData,
    tyProjectForm,
    phaseOptions,
    isAddparameter,
    getPhaseList,
    getNotSpecialChar,
    validatorName,
    validatorNumber,
    valideIbaForm,
    getIbaForm,
    queryDevOrderByNumber,
    queryDevOrderDetailByProjectCode,
    getProjectTemplateList,
    getIbaFormpro
  };
}
